<template>
  <div class="exams-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="container">
        <Breadcrumb :items="breadcrumbItems" />
        <div class="header-content">
          <h1 class="page-title">考试中心</h1>
          <p class="page-subtitle">检验学习成果，获得专业认证</p>
        </div>
      </div>
    </div>
    
    <!-- 搜索和筛选 -->
    <div class="search-filter-section">
      <div class="container">
        <div class="search-bar">
          <SearchBox
            v-model="searchKeyword"
            placeholder="搜索考试名称、技能领域..."
            :show-advanced="true"
            :categories="categories"
            :difficulties="difficulties"
            @search="handleSearch"
            @advanced-search="handleAdvancedSearch"
          />
        </div>
        
        <div class="filter-tabs">
          <el-tabs v-model="activeCategory" @tab-change="handleCategoryChange">
            <el-tab-pane label="全部" name="all" />
            <el-tab-pane
              v-for="category in categories"
              :key="category.value"
              :label="category.label"
              :name="category.value"
            />
          </el-tabs>
        </div>
        
        <div class="filter-controls">
          <div class="filter-left">
            <el-select
              v-model="filters.difficulty"
              placeholder="难度等级"
              clearable
              @change="handleFilterChange"
            >
              <el-option
                v-for="difficulty in difficulties"
                :key="difficulty.value"
                :label="difficulty.label"
                :value="difficulty.value"
              />
            </el-select>
            
            <el-select
              v-model="filters.status"
              placeholder="考试状态"
              clearable
              @change="handleFilterChange"
            >
              <el-option label="全部" value="all" />
              <el-option label="未开始" value="not_started" />
              <el-option label="进行中" value="in_progress" />
              <el-option label="已完成" value="completed" />
              <el-option label="已过期" value="expired" />
            </el-select>
            
            <el-select
              v-model="filters.type"
              placeholder="考试类型"
              clearable
              @change="handleFilterChange"
            >
              <el-option label="练习考试" value="practice" />
              <el-option label="正式考试" value="formal" />
              <el-option label="认证考试" value="certification" />
            </el-select>
            
            <el-button
              v-if="hasActiveFilters"
              text
              type="primary"
              @click="clearFilters"
            >
              清除筛选
            </el-button>
          </div>
          
          <div class="filter-right">
            <el-select
              v-model="sortBy"
              placeholder="排序方式"
              @change="handleSortChange"
            >
              <el-option label="综合排序" value="default" />
              <el-option label="最新发布" value="newest" />
              <el-option label="截止时间" value="deadline" />
              <el-option label="难度等级" value="difficulty" />
              <el-option label="参与人数" value="participants" />
            </el-select>
            
            <el-button-group class="view-mode">
              <el-button
                :type="viewMode === 'grid' ? 'primary' : 'default'"
                @click="viewMode = 'grid'"
              >
                <el-icon><Grid /></el-icon>
              </el-button>
              <el-button
                :type="viewMode === 'list' ? 'primary' : 'default'"
                @click="viewMode = 'list'"
              >
                <el-icon><List /></el-icon>
              </el-button>
            </el-button-group>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 考试列表 -->
    <div class="exams-content">
      <div class="container">
        <!-- 结果统计 -->
        <div class="results-info" v-if="!loading">
          <span class="results-count">
            共找到 <strong>{{ total }}</strong> 场考试
          </span>
          <div class="active-filters" v-if="activeFilters.length > 0">
            <span class="filter-label">当前筛选：</span>
            <el-tag
              v-for="filter in activeFilters"
              :key="filter.key"
              closable
              @close="removeFilter(filter.key)"
            >
              {{ filter.label }}
            </el-tag>
          </div>
        </div>
        
        <!-- 考试网格/列表 -->
        <div
          class="exams-container"
          :class="{
            'grid-view': viewMode === 'grid',
            'list-view': viewMode === 'list'
          }"
          v-loading="loading"
        >
          <template v-if="exams.length > 0">
            <ExamCard
              v-for="exam in exams"
              :key="exam.id"
              :exam="exam"
              :view-mode="viewMode"
              @click="viewExam(exam.id)"
              @start="handleStartExam"
              @continue="handleContinueExam"
              @view-result="handleViewResult"
            />
          </template>
          
          <!-- 空状态 -->
          <div v-else-if="!loading" class="empty-state">
            <el-empty
              description="暂无符合条件的考试"
              :image-size="120"
            >
              <template #image>
                <el-icon :size="120" color="var(--el-color-info)">
                  <EditPen />
                </el-icon>
              </template>
              <el-button type="primary" @click="clearFilters">
                清除筛选条件
              </el-button>
            </el-empty>
          </div>
        </div>
        
        <!-- 分页 -->
        <div class="pagination-container" v-if="total > 0">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :total="total"
            :page-sizes="[12, 24, 36, 48]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handlePageSizeChange"
            @current-change="handlePageChange"
          />
        </div>
      </div>
    </div>
    
    <!-- 我的考试记录 -->
    <div class="my-exams-section" v-if="userStore.isLoggedIn && myExams.length > 0">
      <div class="container">
        <div class="section-header">
          <h2 class="section-title">我的考试记录</h2>
          <p class="section-subtitle">查看您的考试历史和成绩</p>
          <el-button type="primary" text @click="viewAllMyExams">
            查看全部
          </el-button>
        </div>
        
        <div class="my-exams-list">
          <div
            v-for="exam in myExams.slice(0, 4)"
            :key="exam.id"
            class="my-exam-item"
            @click="viewExamResult(exam.id)"
          >
            <div class="exam-info">
              <div class="exam-title">{{ exam.title }}</div>
              <div class="exam-meta">
                <span class="exam-date">{{ formatDate(exam.completedAt) }}</span>
                <el-tag
                  :type="getScoreType(exam.score)"
                  size="small"
                >
                  {{ exam.score }}分
                </el-tag>
              </div>
            </div>
            <div class="exam-result">
              <div class="score-circle">
                <el-progress
                  type="circle"
                  :percentage="exam.score"
                  :width="60"
                  :stroke-width="6"
                  :color="getScoreColor(exam.score)"
                >
                  <template #default="{ percentage }">
                    <span class="score-text">{{ percentage }}</span>
                  </template>
                </el-progress>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 推荐考试 -->
    <div class="recommended-section" v-if="recommendedExams.length > 0">
      <div class="container">
        <div class="section-header">
          <h2 class="section-title">推荐考试</h2>
          <p class="section-subtitle">基于您的学习进度推荐</p>
        </div>
        
        <div class="recommended-exams">
          <ExamCard
            v-for="exam in recommendedExams"
            :key="exam.id"
            :exam="exam"
            view-mode="grid"
            @click="viewExam(exam.id)"
            @start="handleStartExam"
            @continue="handleContinueExam"
            @view-result="handleViewResult"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, watch, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Grid, List, EditPen } from '@element-plus/icons-vue'
import { useExamStore } from '@/stores/exam'
import { useUserStore } from '@/stores/user'
import SearchBox from '@/components/common/SearchBox.vue'
import Breadcrumb from '@/components/common/Breadcrumb.vue'
import ExamCard from '@/components/exam/ExamCard.vue'
import { formatDate } from '@/utils/format'

const router = useRouter()
const route = useRoute()
const examStore = useExamStore()
const userStore = useUserStore()

// 响应式数据
const loading = ref(false)
const searchKeyword = ref('')
const activeCategory = ref('all')
const viewMode = ref('grid')
const sortBy = ref('default')
const currentPage = ref(1)
const pageSize = ref(12)
const total = ref(0)
const exams = ref([])
const myExams = ref([])
const recommendedExams = ref([])

// 筛选条件
const filters = reactive({
  difficulty: '',
  status: 'all',
  type: ''
})

// 面包屑导航
const breadcrumbItems = ref([
  { title: '首页', path: '/' },
  { title: '考试中心', path: '/exams' }
])

// 分类选项
const categories = ref([
  { label: '前端开发', value: 'frontend' },
  { label: '后端开发', value: 'backend' },
  { label: '移动开发', value: 'mobile' },
  { label: '数据科学', value: 'data-science' },
  { label: '人工智能', value: 'ai' },
  { label: '云计算', value: 'cloud' },
  { label: '网络安全', value: 'security' },
  { label: '产品设计', value: 'design' },
  { label: '项目管理', value: 'management' }
])

// 难度选项
const difficulties = ref([
  { label: '入门', value: 'beginner' },
  { label: '初级', value: 'elementary' },
  { label: '中级', value: 'intermediate' },
  { label: '高级', value: 'advanced' },
  { label: '专家', value: 'expert' }
])

// 计算属性
const hasActiveFilters = computed(() => {
  return Object.values(filters).some(value => value && value !== 'all') ||
         activeCategory.value !== 'all' ||
         searchKeyword.value.trim()
})

const activeFilters = computed(() => {
  const result = []
  
  if (searchKeyword.value.trim()) {
    result.push({
      key: 'keyword',
      label: `关键词: ${searchKeyword.value}`
    })
  }
  
  if (activeCategory.value !== 'all') {
    const category = categories.value.find(c => c.value === activeCategory.value)
    if (category) {
      result.push({
        key: 'category',
        label: `分类: ${category.label}`
      })
    }
  }
  
  if (filters.difficulty) {
    const difficulty = difficulties.value.find(d => d.value === filters.difficulty)
    if (difficulty) {
      result.push({
        key: 'difficulty',
        label: `难度: ${difficulty.label}`
      })
    }
  }
  
  if (filters.status !== 'all') {
    const statusMap = {
      not_started: '未开始',
      in_progress: '进行中',
      completed: '已完成',
      expired: '已过期'
    }
    result.push({
      key: 'status',
      label: `状态: ${statusMap[filters.status]}`
    })
  }
  
  if (filters.type) {
    const typeMap = {
      practice: '练习考试',
      formal: '正式考试',
      certification: '认证考试'
    }
    result.push({
      key: 'type',
      label: `类型: ${typeMap[filters.type]}`
    })
  }
  
  return result
})

// 方法
const fetchExams = async () => {
  try {
    loading.value = true
    
    const params = {
      page: currentPage.value,
      limit: pageSize.value,
      keyword: searchKeyword.value.trim(),
      category: activeCategory.value !== 'all' ? activeCategory.value : '',
      difficulty: filters.difficulty,
      status: filters.status !== 'all' ? filters.status : '',
      type: filters.type,
      sortBy: sortBy.value
    }
    
    await examStore.fetchExamList(params)
    
    exams.value = examStore.examList
    total.value = examStore.total
  } catch (error) {
    ElMessage.error('获取考试列表失败')
    console.error('获取考试列表失败:', error)
  } finally {
    loading.value = false
  }
}

const fetchMyExams = async () => {
  try {
    if (userStore.isLoggedIn) {
      await examStore.fetchMyExams()
      myExams.value = examStore.myExams
    }
  } catch (error) {
    console.error('获取我的考试记录失败:', error)
  }
}

const fetchRecommendedExams = async () => {
  try {
    await examStore.fetchRecommendedExams()
    recommendedExams.value = examStore.recommendedExams.slice(0, 4)
  } catch (error) {
    console.error('获取推荐考试失败:', error)
  }
}

const handleSearch = (searchData) => {
  searchKeyword.value = searchData.keyword
  currentPage.value = 1
  fetchExams()
}

const handleAdvancedSearch = (searchData) => {
  searchKeyword.value = searchData.keyword
  
  // 应用高级筛选条件
  if (searchData.filters.category) {
    activeCategory.value = searchData.filters.category
  }
  if (searchData.filters.difficulty) {
    filters.difficulty = searchData.filters.difficulty
  }
  if (searchData.filters.sortBy) {
    sortBy.value = searchData.filters.sortBy
  }
  
  currentPage.value = 1
  fetchExams()
}

const handleCategoryChange = (category) => {
  activeCategory.value = category
  currentPage.value = 1
  fetchExams()
}

const handleFilterChange = () => {
  currentPage.value = 1
  fetchExams()
}

const handleSortChange = () => {
  currentPage.value = 1
  fetchExams()
}

const handlePageChange = (page) => {
  currentPage.value = page
  fetchExams()
  
  // 滚动到顶部
  window.scrollTo({ top: 0, behavior: 'smooth' })
}

const handlePageSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  fetchExams()
}

const clearFilters = () => {
  searchKeyword.value = ''
  activeCategory.value = 'all'
  Object.assign(filters, {
    difficulty: '',
    status: 'all',
    type: ''
  })
  sortBy.value = 'default'
  currentPage.value = 1
  fetchExams()
}

const removeFilter = (filterKey) => {
  switch (filterKey) {
    case 'keyword':
      searchKeyword.value = ''
      break
    case 'category':
      activeCategory.value = 'all'
      break
    case 'difficulty':
      filters.difficulty = ''
      break
    case 'status':
      filters.status = 'all'
      break
    case 'type':
      filters.type = ''
      break
  }
  
  currentPage.value = 1
  fetchExams()
}

const viewExam = (examId) => {
  router.push(`/exams/${examId}`)
}

const handleStartExam = async (examId) => {
  try {
    if (!userStore.isLoggedIn) {
      ElMessage.warning('请先登录')
      router.push('/login')
      return
    }
    
    // 确认开始考试
    await ElMessageBox.confirm(
      '开始考试后将无法暂停，请确保您有足够的时间完成考试。',
      '确认开始考试',
      {
        confirmButtonText: '开始考试',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await examStore.startExam(examId)
    router.push(`/exam/${examId}`)
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '开始考试失败')
    }
  }
}

const handleContinueExam = (examId) => {
  router.push(`/exam/${examId}`)
}

const handleViewResult = (examId) => {
  router.push(`/exam/${examId}/result`)
}

const viewAllMyExams = () => {
  router.push('/profile/exams')
}

const viewExamResult = (examId) => {
  router.push(`/exam/${examId}/result`)
}

const getScoreType = (score) => {
  if (score >= 90) return 'success'
  if (score >= 80) return 'warning'
  if (score >= 60) return 'info'
  return 'danger'
}

const getScoreColor = (score) => {
  if (score >= 90) return '#67c23a'
  if (score >= 80) return '#e6a23c'
  if (score >= 60) return '#409eff'
  return '#f56c6c'
}

// 监听路由变化
watch(
  () => route.query,
  (newQuery) => {
    if (newQuery.q) {
      searchKeyword.value = newQuery.q
    }
    if (newQuery.category) {
      activeCategory.value = newQuery.category
    }
    if (newQuery.difficulty) {
      filters.difficulty = newQuery.difficulty
    }
    if (newQuery.sort) {
      sortBy.value = newQuery.sort
    }
    
    fetchExams()
  },
  { immediate: true }
)

// 监听用户登录状态
watch(
  () => userStore.isLoggedIn,
  (isLoggedIn) => {
    if (isLoggedIn) {
      fetchMyExams()
    } else {
      myExams.value = []
    }
  },
  { immediate: true }
)

// 生命周期
onMounted(async () => {
  await Promise.all([
    fetchExams(),
    fetchRecommendedExams(),
    userStore.isLoggedIn ? fetchMyExams() : Promise.resolve()
  ])
})
</script>

<style lang="scss" scoped>
.exams-page {
  min-height: 100vh;
  background: var(--el-bg-color-page);
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

// 页面头部
.page-header {
  background: var(--el-bg-color);
  padding: 20px 0 30px;
  border-bottom: 1px solid var(--el-border-color-lighter);
  
  .header-content {
    margin-top: 16px;
    
    .page-title {
      font-size: 2rem;
      font-weight: 600;
      color: var(--el-text-color-primary);
      margin-bottom: 8px;
    }
    
    .page-subtitle {
      color: var(--el-text-color-regular);
      font-size: 1.1rem;
    }
  }
}

// 搜索筛选区域
.search-filter-section {
  background: var(--el-bg-color);
  padding: 24px 0;
  border-bottom: 1px solid var(--el-border-color-lighter);
  
  .search-bar {
    margin-bottom: 24px;
  }
  
  .filter-tabs {
    margin-bottom: 20px;
    
    :deep(.el-tabs__header) {
      margin-bottom: 0;
    }
    
    :deep(.el-tabs__nav-wrap::after) {
      display: none;
    }
  }
  
  .filter-controls {
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 16px;
    
    .filter-left {
      display: flex;
      align-items: center;
      gap: 12px;
      flex: 1;
      
      .el-select {
        width: 140px;
      }
    }
    
    .filter-right {
      display: flex;
      align-items: center;
      gap: 12px;
      
      .el-select {
        width: 140px;
      }
      
      .view-mode {
        .el-button {
          padding: 8px 12px;
        }
      }
    }
  }
}

// 考试内容区域
.exams-content {
  padding: 24px 0;
  
  .results-info {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    padding: 16px 0;
    border-bottom: 1px solid var(--el-border-color-lighter);
    
    .results-count {
      color: var(--el-text-color-regular);
      font-size: 14px;
    }
    
    .active-filters {
      display: flex;
      align-items: center;
      gap: 8px;
      
      .filter-label {
        color: var(--el-text-color-secondary);
        font-size: 14px;
      }
      
      .el-tag {
        margin-left: 4px;
      }
    }
  }
  
  .exams-container {
    min-height: 400px;
    
    &.grid-view {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
      gap: 24px;
    }
    
    &.list-view {
      display: flex;
      flex-direction: column;
      gap: 16px;
    }
  }
  
  .empty-state {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 300px;
  }
  
  .pagination-container {
    display: flex;
    justify-content: center;
    margin-top: 40px;
    padding-top: 24px;
    border-top: 1px solid var(--el-border-color-lighter);
  }
}

// 我的考试记录
.my-exams-section {
  background: var(--el-bg-color);
  padding: 60px 0;
  border-top: 1px solid var(--el-border-color-lighter);
  
  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 40px;
    
    .section-title {
      font-size: 1.8rem;
      font-weight: 600;
      color: var(--el-text-color-primary);
      margin-bottom: 8px;
    }
    
    .section-subtitle {
      color: var(--el-text-color-regular);
      font-size: 1rem;
    }
  }
  
  .my-exams-list {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
    gap: 20px;
    
    .my-exam-item {
      background: var(--el-bg-color-page);
      border: 1px solid var(--el-border-color-lighter);
      border-radius: 8px;
      padding: 20px;
      cursor: pointer;
      transition: all 0.3s;
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      &:hover {
        border-color: var(--el-color-primary);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
      }
      
      .exam-info {
        flex: 1;
        
        .exam-title {
          font-weight: 500;
          color: var(--el-text-color-primary);
          margin-bottom: 8px;
          font-size: 16px;
        }
        
        .exam-meta {
          display: flex;
          align-items: center;
          gap: 12px;
          
          .exam-date {
            color: var(--el-text-color-secondary);
            font-size: 14px;
          }
        }
      }
      
      .exam-result {
        .score-circle {
          .score-text {
            font-size: 12px;
            font-weight: 600;
          }
        }
      }
    }
  }
}

// 推荐考试区域
.recommended-section {
  background: var(--el-bg-color);
  padding: 60px 0;
  border-top: 1px solid var(--el-border-color-lighter);
  
  .section-header {
    text-align: center;
    margin-bottom: 40px;
    
    .section-title {
      font-size: 1.8rem;
      font-weight: 600;
      color: var(--el-text-color-primary);
      margin-bottom: 8px;
    }
    
    .section-subtitle {
      color: var(--el-text-color-regular);
      font-size: 1rem;
    }
  }
  
  .recommended-exams {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
    gap: 24px;
  }
}

// 响应式设计
@media (max-width: 1024px) {
  .filter-controls {
    flex-direction: column;
    align-items: stretch !important;
    gap: 16px !important;
    
    .filter-left,
    .filter-right {
      justify-content: flex-start;
    }
    
    .filter-right {
      justify-content: space-between;
    }
  }
  
  .results-info {
    flex-direction: column !important;
    align-items: flex-start !important;
    gap: 12px;
  }
  
  .my-exams-section {
    .section-header {
      flex-direction: column;
      align-items: flex-start;
      gap: 16px;
    }
  }
}

@media (max-width: 768px) {
  .container {
    padding: 0 16px;
  }
  
  .page-header {
    .header-content {
      .page-title {
        font-size: 1.5rem;
      }
      
      .page-subtitle {
        font-size: 1rem;
      }
    }
  }
  
  .filter-controls {
    .filter-left {
      flex-wrap: wrap;
      
      .el-select {
        width: 120px;
      }
    }
  }
  
  .exams-container {
    &.grid-view {
      grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
      gap: 16px;
    }
  }
  
  .my-exams-list {
    grid-template-columns: 1fr;
    
    .my-exam-item {
      flex-direction: column;
      align-items: flex-start;
      gap: 16px;
      
      .exam-result {
        align-self: flex-end;
      }
    }
  }
  
  .recommended-exams {
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)) !important;
    gap: 16px !important;
  }
}

@media (max-width: 480px) {
  .search-filter-section {
    padding: 16px 0;
  }
  
  .filter-controls {
    .filter-left {
      .el-select {
        width: 100px;
        font-size: 12px;
      }
    }
    
    .filter-right {
      .el-select {
        width: 100px;
        font-size: 12px;
      }
    }
  }
  
  .exams-container {
    &.grid-view {
      grid-template-columns: 1fr;
    }
  }
  
  .recommended-exams {
    grid-template-columns: 1fr !important;
  }
  
  .pagination-container {
    :deep(.el-pagination) {
      .el-pagination__sizes,
      .el-pagination__jump {
        display: none;
      }
    }
  }
}
</style>